import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form, Modal } from 'antd';
import { useEffect, useRef, useState } from 'react';
import FileUploader from '@/components/UploadFile';
import {
  createCategory,
  deleteCategory,
  listCategories,
  updateCategory,
} from '@/services/mall/api';

const CategoryForm = ({
  open,
  onCancel,
  onRefresh,
  editingRecord,
  defaultFormValues,
}: {
  open: boolean;
  onCancel: () => void;
  onRefresh: () => void;
  editingRecord?: ProductType.CategoryList | null;
  defaultFormValues?: Partial<ProductType.CategoryCreate>;
}) => {
  const [form] = Form.useForm();

  // 表单初始化
  useEffect(() => {
    if (open) {
      // 编辑
      if (editingRecord) {
        form.setFieldsValue({
          ...editingRecord,
          icon: editingRecord.icon || '', // 确保空值时为字符串而非 undefined
          image: editingRecord.image || '',
        });
      } else {
        // 新增
        form.resetFields();
        if (defaultFormValues) {
          form.setFieldsValue(defaultFormValues);
        }
      }
    }
  }, [open, editingRecord, defaultFormValues, form]);

  // 是否是编辑
  const isEditing = !!editingRecord;

  return (
    <ModalForm
      title={isEditing ? '编辑分类' : '新建分类'}
      form={form}
      open={open}
      autoFocusFirstInput
      modalProps={{
        destroyOnHidden: true,
        onCancel,
      }}
      onFinish={async (values) => {
        console.log('表单值:', values);
        // 直接从表单值中获取 icon 和 image（已由 UploadFile 的 onChange 同步）
        const submitData = {
          ...values,
          // 编辑模式补充 id
          ...(isEditing && { id: editingRecord?.id }),
          // 新增模式补充 parentId
          ...(!isEditing &&
            defaultFormValues?.parentId && {
              parentId: defaultFormValues.parentId,
            }),
        };
        // 打印调试：确认是否有 icon 和 image
        console.log('提交数据:', submitData);
        if (isEditing) {
          await updateCategory(submitData);
        } else {
          await createCategory(submitData);
        }
        onRefresh();
        onCancel();
      }}
    >
      <ProForm.Group>
        <ProFormText width="md" name="name" label="名称" />
        <ProFormText width="md" name="type" label="类型" />

        {/* 图标上传 */}
        <ProForm.Item
          name="icon"
          label="图标"
          valuePropName="value"
          trigger="onChange"
        >
          <FileUploader
            listType="picture-card"
            fileType="image"
            useBase64={true}
            maxCount={1}
            showPreview={true}
            // 编辑时优先用表单值，否则用 editingRecord 的值
            value={form.getFieldValue('icon') || editingRecord?.icon || ''}
            // 同步上传变化后的值
            onChange={(value) => {
              console.log('FileUploader 变化:', value);
              form.setFieldValue('icon', value ?? '');
            }}
          />
        </ProForm.Item>

        {/* 图片上传 */}
        <ProForm.Item
          name="image"
          label="图片"
          valuePropName="value"
          trigger="onChange"
        >
          <FileUploader
            listType="picture-card"
            fileType="image"
            useBase64={true}
            maxCount={1}
            showPreview={true}
            value={form.getFieldValue('image') || editingRecord?.image || ''}
            onChange={(value) => form.setFieldValue('image', value ?? '')}
          />
        </ProForm.Item>

        <ProFormSelect
          width="md"
          name="status"
          label="状态"
          valueEnum={{
            0: '正常',
            1: '停用',
          }}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

export default () => {
  const actionRef = useRef<ActionType>(null);
  const [formVisible, setFormVisible] = useState(false);
  const [editingRecord, setEditingRecord] =
    useState<ProductType.CategoryList | null>(null);
  const [defaultFormValues, setDefaultFormValues] = useState<
    Partial<ProductType.CategoryCreate>
  >({});

  const refreshTable = () => {
    actionRef.current?.reload();
  };

  const handleOpenForm = () => {
    setFormVisible(true);
  };

  const handleCloseForm = () => {
    setFormVisible(false);
    setEditingRecord(null);
    setDefaultFormValues({});
  };

  const handleRowAdd = (parentId?: number) => {
    setDefaultFormValues(parentId ? { parentId } : {});
    handleOpenForm();
  };
  const handleRowEdit = (record: ProductType.CategoryList) => {
    setEditingRecord(record);
    handleOpenForm();
  };
  const handleRowDel = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await deleteCategory(id);
        refreshTable();
      },
    });
  };

  const columns: ProColumns<ProductType.CategoryList>[] = [
    { title: '名称', dataIndex: 'name' },
    { title: '类型', dataIndex: 'type' },
    { title: '图标', dataIndex: 'icon', valueType: 'image' },
    { title: '图片', dataIndex: 'image', valueType: 'image' },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '正常' },
        1: { text: '停用', status: 'Default' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_text, record) => [
        <a key="add" onClick={() => handleRowAdd(record.id)}>
          添加
        </a>,
        <a key="edit" onClick={() => handleRowEdit(record)}>
          编辑
        </a>,
        <a
          key="delete"
          style={{ color: '#f56c6c' }}
          onClick={() => {
            if (record.id != null) {
              handleRowDel(record.id);
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  return (
    <ProTable<ProductType.CategoryList>
      actionRef={actionRef}
      request={async (_params, _sort, _filter) => {
        const msg = await listCategories();
        return {
          data: msg,
          success: true,
        };
      }}
      rowKey="id"
      pagination={{
        showQuickJumper: true,
      }}
      columns={columns}
      search={{ labelWidth: 'auto' }}
      dateFormatter="string"
      headerTitle="分类管理"
      toolBarRender={() => [
        <Button
          type="primary"
          key="button"
          icon={<PlusOutlined />}
          onClick={() => handleOpenForm()}
        >
          添加
        </Button>,
        formVisible && (
          <CategoryForm
            key="category-form"
            open={formVisible}
            onCancel={handleCloseForm}
            onRefresh={refreshTable}
            editingRecord={editingRecord}
            defaultFormValues={defaultFormValues}
          />
        ),
      ]}
    />
  );
};
